<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>购物车</title>
  <style>
    thead {
      background-color: #f5f5f5;
    }

    th,
    td {
      border: 1px solid #aaa;
      padding: 8px 12px;
      text-align: center;
    }
  </style>
</head>

<body>
  <table>
    <thead>
      <tr>
        <th>编号</th>
        <th>书籍名称</th>
        <th>出版日期</th>
        <th>价格</th>
        <th>购买数量</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
  <h2 class="price">总价格:¥<span class="price-count">0</span></h2>
  <script>
    //1.先拿到数据
    let books = [
      {
        id: 1,
        name: '《算法导论》',
        date: '2006-09',
        price: 85.0,
        count: 3,
      },
      {
        id: 2,
        name: '《UNIX编程艺术》',
        date: '2006-02',
        price: 59.0,
        count: 2,
      },
      {
        id: 3,
        name: '《编程珠玑》',
        date: '2008-10',
        price: 39.0,
        count: 5,
      },
      {
        id: 4,
        name: '《代码大全》',
        date: '2006-03',
        price: 128.0,
        count: 8,
      },
    ];

    let tableEl = document.querySelector("table");
    let priceCount = document.querySelector(".price-count");
    let tbody = document.querySelector("tbody");

    // 将数据渲染到页面上
    books.forEach(ele => {
      let tr = document.createElement("tr");
      for (let key in ele) {
        let td = document.createElement("td");
        let value = ele[key];
        if (key === "price") {
          value = "￥" + ele[key];
        }
        td.textContent = value;
        tr.append(td);
      }
      let delTd = document.createElement("td");
      let delBtn = document.createElement("button")
      delBtn.textContent = "删除";
      delTd.append(delBtn);
      tr.append(delTd);
      delBtn.onclick = (e) => {
        let delTr = e.target.parentElement.parentElement;
        let delTrIndex = delTr.sectionRowIndex;
        delTr.remove();
        books.splice(delTrIndex, 1);
        countPrice();
      }
      tbody.append(tr);
    });

    // 页面打开后先调用一次，显示当前总价
    countPrice()

    // 计算总价格
    // function countPrice() {
    //   // 获取当前页面渲染出来的tbody里的全部商品
    //   let tbodyData = [...document.querySelectorAll("tbody tr")];
    //   // 遍历所有商品的总价
    //   let total = tbodyData.reduce((prev, ele,index) => {
    //     return prev + ele.children[3].innerHTML * ele.children[4].innerHTML;
    //   }, 0);
    //   // 将计算好的总价显示到页面上
    //   price.innerHTML = total;
    // }

    function countPrice() {
      // 将计算好的总价显示到页面上
      priceCount.textContent = books.reduce((prev, ele) => prev + ele.price * ele.count, 0);
    }
  </script>
</body>

</html>